package com.projectplace;

/*
 * Copyright (c) 2011 Projectplace International AB
 * Permission is hereby granted, free of charge, to any person 
 * obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, 
 * publish, distribute, sublicense, and/or sell copies of the Software, 
 * and to permit persons to whom the Software is furnished to do so, 
 * subject to the following conditions:The above copyright notice and this 
 * permission notice shall be included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import com.projectplace.GUI.Contacts;
import com.projectplace.GUI.Conversations;
import com.projectplace.GUI.DocumentsActivity;
import com.projectplace.api.OAUTH;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.Button;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class ProjectPlace extends TabActivity {

	private SharedPreferences mSettings;
	private OAuthConsumer mConsumer = null;
	private final static String TAG = "ProjectPlace";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.main);

		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.my_title);
		Button buttonTop = (Button) findViewById(R.id.buttonTitle);
		buttonTop.setVisibility(4);

		mSettings = getSharedPreferences(OAUTH.PREFS, Context.MODE_PRIVATE);
  
		mConsumer = new CommonsHttpOAuthConsumer(
				Keys.PROJECTPLACE_CONSUMER_KEY,
				Keys.PROJECTPLACE_CONSUMER_SECRET);

		if (mSettings.contains(OAUTH.USER_TOKEN)
				&& mSettings.contains(OAUTH.USER_SECRET)) {
			mConsumer.setTokenWithSecret(
					mSettings.getString(OAUTH.USER_TOKEN, null),
					mSettings.getString(OAUTH.USER_SECRET, null));
			SingeltonPPClient.setConsumer(mConsumer);
		} else {
			Intent i = new Intent(this, OAUTH.class);
			startActivity(i);

		}
   
		final TabHost tabHost = getTabHost(); // The activity TabHost
		TabHost.TabSpec spec; // Resusable TabSpec for each tab
		Intent intent; // Reusable Intent for each tab

		// Create an Intent to launch an Activity for the tab (to be reused)
		intent = new Intent().setClass(this, Conversations.class);

		// Initialize a TabSpec for each tab and add it to the TabHost
		spec = tabHost
				.newTabSpec("conversations")
				.setIndicator("Conversations",
						reSize(R.drawable.chatsicon, 80, 120))
				.setContent(intent);

		tabHost.addTab(spec);

		// Do the same for the other tabs
		intent = new Intent().setClass(this, DocumentsActivity.class);
		spec = tabHost
				.newTabSpec("documents")
				.setIndicator("Documents",
						reSize(R.drawable.documentsicon, 80, 120))
				.setContent(intent);
		tabHost.addTab(spec);

		// Do the same for the other tabs
		intent = new Intent().setClass(this, Contacts.class);
		spec = tabHost
				.newTabSpec("contacts")
				.setIndicator("Contacts", reSize(R.drawable.groupicon, 80, 120))
				.setContent(intent);
		tabHost.addTab(spec);

		tabHost.getTabWidget().getChildAt(0)
				.setBackgroundColor(Color.parseColor("#FFFFFF"));
		tabHost.getTabWidget().getChildAt(1)
				.setBackgroundColor(Color.parseColor("#F2F2F2"));
		tabHost.getTabWidget().getChildAt(2)
				.setBackgroundColor(Color.parseColor("#F2F2F2"));

		for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
			TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i)
					.findViewById(android.R.id.title);
			tv.setTextColor(Color.BLACK);
		}
		tabHost.setOnTabChangedListener(new OnTabChangeListener() {
			public void onTabChanged(String tabId) {
				// TODO Auto-generated method stub
				for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
					tabHost.getTabWidget().getChildAt(i)
							.setBackgroundColor(Color.parseColor("#F2F2F2")); // unselected
				}
				tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab())
						.setBackgroundColor(Color.WHITE); // selected
			}
		});

		tabHost.setCurrentTab(0);
	}

	@SuppressWarnings("unused")
	private void cleanUp() {
		/*for (String s : this.fileList()) {
			this.deleteFile(s);
		}*/

		SharedPreferences.Editor editor = getSharedPreferences(OAUTH.PREFS,
				Context.MODE_PRIVATE).edit();
		editor.remove(OAUTH.USER_TOKEN);
		editor.remove(OAUTH.USER_SECRET);
		editor.commit();

		Toast.makeText(getBaseContext(), "All data DELETED!!",
				Toast.LENGTH_SHORT).show();
	}

	public Drawable reSize(int id, int newHeight, int newWidth) {
		// load the origial BitMap
		Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), id);

		int width = bitmapOrg.getWidth();
		int height = bitmapOrg.getHeight();

		// calculate the scale - in this case = 0.4f
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		// createa matrix for the manipulation
		Matrix matrix = new Matrix();
		// resize the bit map
		matrix.postScale(scaleWidth, scaleHeight);

		// recreate the new Bitmap
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width,
				height, matrix, true);

		// make a Drawable from Bitmap to allow to set the BitMap
		// to the ImageView, ImageButton or what ever
		return new BitmapDrawable(resizedBitmap);
	}

	public void initiateOAUTH() {
		// We look for saved user keys
		Log.d(TAG, "innan if");
		if (mSettings.contains(OAUTH.USER_TOKEN)
				&& mSettings.contains(OAUTH.USER_SECRET)) {
			Log.d(TAG, "efter if");
			if (!(mSettings.getString(OAUTH.USER_TOKEN, null) == null && mSettings
					.getString(OAUTH.USER_SECRET, null) == null)) {
				Log.d(TAG, "De Finns token och secret");
				mConsumer.setTokenWithSecret(
						mSettings.getString(OAUTH.USER_TOKEN, null),
						mSettings.getString(OAUTH.USER_SECRET, null));
				SingeltonPPClient.setConsumer(mConsumer);
			}
		} else {
			Log.d(TAG, "de finns inte");
			Intent i = new Intent(this, OAUTH.class);
			Log.d(TAG, "skapat ny intent");
			startActivity(i);
		}
	}
}
